﻿//-----------------------------------------------------------------------
// <copyright file="MessagingRepository.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Infrastructure.SmtpPopImap.Repositories{    using System;
    using System.Linq;
    using System.Net;
    using System.Net.Mail;
    using AbstractSaaSTemplate.Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Models.ValueObjects;
    using AbstractSaaSTemplate.Domain.Repositories;
    using AbstractSaaSTemplate.Infrastructure.AspNetProviders.Exceptions;

    /// <summary>
    /// Implements 'IMessagingRepository' and all its contract, providing
    /// data accessibility to the aggregate 'Messaging'.
    /// </summary>
    public class MessagingRepository : IMessagingRepository
    {
        /// <summary>
        /// Initializes a new instance of the MessagingRepository class.
        /// </summary>
        /// <param name="loaderForSmtpHost">The delegate capable of retrieving the host of the smtp.</param>
        /// <param name="loaderForSmtpPort">The delegate capable of retrieving the port to access the smtp.</param>
        /// <param name="loaderForSmtpCredential">The delegate capable of retrieving the credentials for the smtp.</param>
        /// <param name="loaderForSmtpRequiresSsl">The delegate capable of retrieving the value indicating whether smtp server requires ssl.</param>
        public MessagingRepository(
            Func<string> loaderForSmtpHost,
            Func<int> loaderForSmtpPort,
            Func<NetworkCredential> loaderForSmtpCredential,
            Func<bool> loaderForSmtpRequiresSsl)
        {
            this.LoaderForSmtpHost = loaderForSmtpHost;
            this.LoaderForSmtpPort = loaderForSmtpPort;
            this.LoaderForSmtpCredential = loaderForSmtpCredential;
            this.LoaderForSmtpRequiresSsl = loaderForSmtpRequiresSsl;
        }

        /// <summary>
        /// Gets the host of the Smtp Server.
        /// </summary>
        public Func<string> LoaderForSmtpHost { get; private set; }

        /// <summary>
        /// Gets the port of the Smtp Server.
        /// </summary>
        public Func<int> LoaderForSmtpPort { get; private set; }

        /// <summary>
        /// Gets the login used to authenticate the session in the Smtp server.
        /// </summary>
        public Func<NetworkCredential> LoaderForSmtpCredential { get; private set; }

        /// <summary>
        /// Gets a value indicating whether the smtp server requires Ssl for authentication or not.
        /// </summary>
        public Func<bool> LoaderForSmtpRequiresSsl { get; private set; }

        /// <summary>
        /// Dispatches immediately a message.
        /// </summary>
        /// <param name="entry">The entry of 'Message' which will be immediately dispatch.</param>
        public void SendMessage(Message entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }

            var typeOfCustomData = entry.CustomData.GetType();
            if (typeOfCustomData == typeof(EmailMessage))
            {
                this.SendEmailMessage(entry);
            }
        }

        /// <summary>
        /// Dispatches immediately an e-mail message.
        /// </summary>
        /// <param name="emailMessage">The e-mail message.</param>
        private void SendEmailMessage(Message emailMessage)
        {
            var emailMessageFrom = emailMessage.FromAddress as EmailAddress;
            var emailMessageToList = emailMessage.ToAddressList.Cast<EmailAddress>();
            var emailMessageCustomData = emailMessage.CustomData as EmailMessage;
            
            using (var message = new MailMessage())
            {
                var from = null as MailAddress;
                if (!string.IsNullOrWhiteSpace(emailMessageFrom.DisplayName))
                {
                    from = new MailAddress(
                        emailMessageFrom.Address,
                        emailMessageFrom.DisplayName);
                }
                else
                {
                    from = new MailAddress(emailMessageFrom.Address);
                }

                message.From = from;
                message.Subject = emailMessageCustomData.Subject;
                message.Body = emailMessageCustomData.Body;

                // we set the custom priorities based on the message priority
                switch (emailMessage.Priority)
                {
                    case AbstractSaaSTemplate.Domain.Models.Enumerators.MessagePriority.High:
                    case AbstractSaaSTemplate.Domain.Models.Enumerators.MessagePriority.Urgent:
                        message.Priority = MailPriority.High;
                        break;
                    case AbstractSaaSTemplate.Domain.Models.Enumerators.MessagePriority.Low:
                        message.Priority = MailPriority.Low;
                        break;
                }

                foreach (var toAddress in emailMessageToList)
                {
                    var to = null as MailAddress;
                    if (!string.IsNullOrWhiteSpace(toAddress.DisplayName))
                    {
                        to = new MailAddress(toAddress.Address, toAddress.DisplayName);
                    }
                    else
                    {
                        to = new MailAddress(toAddress.Address);
                    }

                    message.To.Add(to);
                }

                var host = this.LoaderForSmtpHost();
                var port = this.LoaderForSmtpPort();
                if (port == default(int))
                {
                    port = 25;
                }

                var requiresSsl = this.LoaderForSmtpRequiresSsl();
                var credential = this.LoaderForSmtpCredential();

                var smtp = new SmtpClient(host, port);
                using (smtp)
                {
                    smtp.EnableSsl = requiresSsl;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

                    if (credential == null)
                    {
                        smtp.UseDefaultCredentials = true;
                    }
                    else
                    {
                        smtp.Credentials = credential;
                    }

                    try
                    {
                        smtp.Send(message);
                    }
                    catch (Exception ex)
                    {
                        throw new FailedToDispatchMailMessageException(ex);
                    }
                }
            }
        }
    }
}


